package com.chookss.home;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.WebCommonActivity;
import com.chookss.base.StaticClass;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.entity.DynamicEntity;
import com.chookss.home.entity.GalleryListEntity;
import com.chookss.home.entity.HomeBannerEntity;
import com.chookss.home.entity.NavigationEntity;
import com.chookss.home.gallery.adapter.GalleryHomeAdapter;
import com.chookss.home.knowledge.KnowledgeMoreFunctionActivity;
import com.chookss.home.knowledge.LookFragment;
import com.chookss.home.knowledge.NavigationKnowledgeAdapter;
import com.chookss.home.knowledge.ScoreRankActivity;
import com.chookss.home.knowledge.UploadFragment;
import com.chookss.home.knowledge.adaper.DynamicAdapter;
import com.chookss.home.knowledge.adaper.KnowledgeMoreFunctionAdapter;
import com.chookss.home.other.ScanActivity;
import com.chookss.home.search.SearchRecordActivity;
import com.chookss.mine.entity.MineInfoEntity;
import com.chookss.mine.set.AccountActivity;
import com.chookss.mine.set.UserInfosActivity;
import com.chookss.mvp.presenter.HomeKnowledgeFragmentPresenter;
import com.chookss.mvp.view.IHomeKnowledgeView;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.Utils;
import com.chookss.view.AutoHeightViewPager;
import com.chookss.view.CircleImageView;
import com.chookss.view.ColorFlipPagerTitleView;
import com.chookss.view.MyViewPagerAdapter;
import com.chookss.view.NoticeDialog;
import com.chookss.view.RecycleViewDivider;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.chookss.view.listener.ShareDialogListener;
import com.google.zxing.integration.android.IntentIntegrator;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.ImmersionFragment;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class HomeKnowledgeFragmentss extends ImmersionFragment implements IHomeKnowledgeView {

    @BindView(R.id.ivHead)
    CircleImageView ivHead;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.ivLevel)
    ImageView ivLevel;
    @BindView(R.id.tvLevel)
    TextView tvLevel;
    @BindView(R.id.llLevel)
    LinearLayout llLevel;
    @BindView(R.id.tvKnowledgeNum)
    TextView tvKnowledgeNum;
    @BindView(R.id.tvRanking)
    TextView tvRanking;
    @BindView(R.id.llRanking)
    LinearLayout llRanking;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.rcvFunction)
    RecyclerView rcvFunction;
    @BindView(R.id.rlTop)
    RelativeLayout rlTop;
    @BindView(R.id.homeBanner)
    Banner homeBanner;
    @BindView(R.id.llBanner)
    LinearLayout llBanner;
    @BindView(R.id.rcvCommonFunction)
    RecyclerView rcvCommonFunction;
    @BindView(R.id.ivCommonFunctionNoData)
    ImageView ivCommonFunctionNoData;
    @BindView(R.id.rcvOfficeTool)
    RecyclerView rcvOfficeTool;
    @BindView(R.id.ivOfficeToolNoData)
    ImageView ivOfficeToolNoData;
    @BindView(R.id.tvDynamic)
    TextView tvDynamic;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.consecutiveScrollerLayout)
    ConsecutiveScrollerLayout consecutiveScrollerLayout;
    @BindView(R.id.smrRf)
    SmartRefreshLayout smrRf;
    @BindView(R.id.ivCompany)
    ImageView ivCompany;
    @BindView(R.id.tvCompany)
    TextView tvCompany;
    @BindView(R.id.llTitle)
    LinearLayout llTitle;
    @BindView(R.id.indicator_view)
    MagicIndicator indicator_view;
    @BindView(R.id.viewPager)
    AutoHeightViewPager viewPager;
    @BindView(R.id.ll_look_upload)
    LinearLayout ll_look_upload;
    @BindView(R.id.ll_look_upload_space)
    View ll_look_upload_space;
    @BindView(R.id.ll_pic)
    LinearLayout ll_pic;
    @BindView(R.id.recyclerPicView)
    RecyclerView recyclerPicView;
    @BindView(R.id.ll_pic_space)
    View ll_pic_space;

    //    @BindView(R.id.spaceViewTop)
//    View spaceViewTop;
    private Context mContext;
    private Activity mActivity;
    Unbinder unbinder;
    private int pageNum = 1;
    private boolean isEnd = false;//是否到底
    private HomeKnowledgeFragmentPresenter homePagePresenter;

    private View emptyView;
    private TextView tvEmpty, tvEmpty2;
    private ImageView ivEmpty;//空布局
    private KnowledgeMoreFunctionAdapter commonFunctionAdapter, officeToolAdapter;
    private ArrayList<NavigationEntity> commonFunctionList = new ArrayList<>();
    private ArrayList<NavigationEntity> officeToolList = new ArrayList<>();
    private NavigationKnowledgeAdapter navigationAdapter;
    private ArrayList<NavigationEntity> navigationEntityList = new ArrayList<>();
    private DynamicAdapter dynamicAdapter;
    private ArrayList<DynamicEntity> dynamicEntities = new ArrayList<>();
    private String DYNAMICTAG = "Home_dynamic_DownloadFile";//下载文件打的标签
    //浏览与上传
    private MyViewPagerAdapter pagerAdapter;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private List<String> titles = new ArrayList<>();
    private LookFragment lookFragment;
    private UploadFragment uploadFragment;
    private CommonNavigator commonNavigator;
    //图片
    private GalleryHomeAdapter galleryHomeAdapter;
    private ArrayList<GalleryListEntity.ImagePathListBean> galleryList = new ArrayList<>();
    public HomeKnowledgeFragmentss() {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = (FragmentActivity) activity;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_homes_knowledge, container, false);
        unbinder = ButterKnife.bind(this, view);
        homePagePresenter = new HomeKnowledgeFragmentPresenter(mActivity, this);
        init();
        EventBus.getDefault().register(this);
        return view;
    }

    private void init() {
        //顶部状态栏 处理
        int statusBarHeight = Utils.getStatusBarHeight(mContext);
        RelativeLayout.LayoutParams llTitleParams = (RelativeLayout.LayoutParams) llTitle.getLayoutParams();
        llTitleParams.height = Utils.dip2px(mContext, 55) + statusBarHeight;
        llTitle.setLayoutParams(llTitleParams);
        llTitle.setPadding(0, statusBarHeight, 0, 0);
//        ViewGroup.LayoutParams rlTopParams = (ViewGroup.LayoutParams) spaceViewTop.getLayoutParams();
//        rlTopParams.height = Utils.dip2px(mContext, 55) + statusBarHeight;
//        spaceViewTop.setLayoutParams(rlTopParams);
        //常用应用及工具
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        rcvCommonFunction.setLayoutManager(gridLayoutManager);
        commonFunctionAdapter = new KnowledgeMoreFunctionAdapter(R.layout.item_home_knowledge_common_tools, mContext, commonFunctionList, 2);
        rcvCommonFunction.setAdapter(commonFunctionAdapter);
        GridLayoutManager gridLayoutManager2 = new GridLayoutManager(mContext, 2);
        rcvOfficeTool.setLayoutManager(gridLayoutManager2);
        officeToolAdapter = new KnowledgeMoreFunctionAdapter(R.layout.item_home_knowledge_common_tools, mContext, officeToolList, 2);
        rcvOfficeTool.setAdapter(officeToolAdapter);
        //浏览及上传列表
        lookFragment = new LookFragment(mContext);
        uploadFragment = new UploadFragment(mContext);
        titles.add("最近浏览");
        titles.add("最近上传");
        fragments.add(lookFragment);
        fragments.add(uploadFragment);
        commonNavigator = new CommonNavigator(mContext);
        commonNavigator.setScrollPivotX(0.65f);
//        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return titles == null ? 0 : titles.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorFlipPagerTitleView(context);
                simplePagerTitleView.setIncludeFontPadding(false);
                simplePagerTitleView.setText(titles.get(index));
                simplePagerTitleView.setPadding(Utils.dip2px(mContext,15),0,Utils.dip2px(mContext,5),0);
                simplePagerTitleView.setTextSize(15);
                simplePagerTitleView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                simplePagerTitleView.setNormalColor(Color.rgb(116, 116, 116));
                simplePagerTitleView.setSelectedColor(Color.rgb(0, 0, 0));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(UIUtil.dip2px(context, 3));
                indicator.setLineWidth(UIUtil.dip2px(context, 15));
                indicator.setRoundRadius(UIUtil.dip2px(context, 1.5));
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setColors(Color.rgb(225, 36, 22));
                return indicator;
            }
        });
        indicator_view.setNavigator(commonNavigator);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                indicator_view.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                indicator_view.onPageSelected(position);
                if (viewPager != null) {
                    viewPager.requestLayout();
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                indicator_view.onPageScrollStateChanged(state);
            }
        });
        pagerAdapter = new MyViewPagerAdapter(getActivity().getSupportFragmentManager(), fragments);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(2);
        //图片列表
        recyclerPicView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        galleryHomeAdapter = new GalleryHomeAdapter(R.layout.item_home_gallery,mContext, galleryList);
        recyclerPicView.setAdapter(galleryHomeAdapter);
        LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) recyclerPicView.getLayoutParams();
        params.height=(int) ((Utils.getScreenWidthPixel(mContext) - Utils.dip2px(mContext, 72)) / 4.5)+ Utils.dip2px(mContext, 15);
        recyclerPicView.setLayoutParams(params);
        ((SimpleItemAnimator) recyclerPicView.getItemAnimator()).setSupportsChangeAnimations(false);
        //动态列表
        recyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_gray)));
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        dynamicAdapter = new DynamicAdapter(mContext, dynamicEntities, DYNAMICTAG);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setAdapter(dynamicAdapter);
        emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_common_empty, recyclerView, false);
        ivEmpty = emptyView.findViewById(R.id.ivEmpty);
        tvEmpty = emptyView.findViewById(R.id.tvEmpty);
        tvEmpty2 = emptyView.findViewById(R.id.tvEmpty2);
        tvEmpty.setText("还没有动态内容");
        tvEmpty2.setText("快去发布吧");
        tvEmpty2.setVisibility(View.VISIBLE);
        LinearLayout.LayoutParams emptyParams = (LinearLayout.LayoutParams) ivEmpty.getLayoutParams();
        emptyParams.setMargins(0, Utils.dip2px(mContext, 20), 0, 0);
        ivEmpty.setLayoutParams(emptyParams);
        LinearLayout.LayoutParams tvEmpty2Params = (LinearLayout.LayoutParams) tvEmpty2.getLayoutParams();
        tvEmpty2Params.setMargins(0, 0, 0, Utils.dip2px(mContext, 140));
        tvEmpty2.setLayoutParams(tvEmpty2Params);

        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@io.reactivex.annotations.NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    pageNum++;
                    homePagePresenter.getDynamicList(pageNum);
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                pageNum = 1;
                isEnd = false;
                if (navigationEntityList.size() == 0) {
                    homePagePresenter.getNavigations();
                } else {
                    homePagePresenter.getResourceNum();
                }
                homePagePresenter.getGalleryList();
                homePagePresenter.getCommonNavigation("1");
                homePagePresenter.getCommonNavigation("2");
                if (lookFragment != null && uploadFragment != null) {
                    lookFragment.setRefresh();
                    uploadFragment.setRefresh();
                }
                homePagePresenter.getDynamicList(pageNum);
            }
        });
//        consecutiveScrollerLayout.setOnVerticalScrollChangeListener(new ConsecutiveScrollerLayout.OnScrollChangeListener() {
//            @Override
//            public void onScrollChange(View v, int scrollY, int oldScrollY, int scrollState) {
//                if (ivHead == null) {
//                    return;
//                }
//                if (scrollY > Utils.dip2px(mContext, 5)) {
//                    llTitle.setBackgroundColor(mContext.getResources().getColor(R.color.main_bg));
//                } else {
//                    llTitle.setBackgroundColor(Color.TRANSPARENT);
//                }
//            }
//        });
        //导航
        GridLayoutManager gridLayoutManager3 = new GridLayoutManager(mContext, 5);
        rcvFunction.setLayoutManager(gridLayoutManager3);
        navigationAdapter = new NavigationKnowledgeAdapter(R.layout.item_home_knowledge_navigation, mContext, navigationEntityList);
        rcvFunction.setAdapter(navigationAdapter);

//        //只要启动调用
//        homePagePresenter.getCostConfig();
//        //水印只有启动和切换账号才获取
//        homePagePresenter.getWatermarkList();
//        homePagePresenter.getOSSkey();
//        homePagePresenter.checkLogin();
        getNOTIFICATION();
        registerBoradcastReceiver();
    }

    @Override
    public void onLazyAfterView() {
        super.onLazyAfterView();
        homePagePresenter.getAllBanner();
        homePagePresenter.getGalleryList();
        homePagePresenter.getDynamicList(pageNum);
        homePagePresenter.getCatalogData();
    }

    @Override
    public void onVisible() {
        super.onVisible();
        if (homePagePresenter == null) {
            return;
        }
        if (navigationEntityList.size() == 0) {
            homePagePresenter.getNavigations();
        } else {
            homePagePresenter.getResourceNum();
        }
        homePagePresenter.getMineInfo();
        homePagePresenter.getCommonNavigation("1");
        homePagePresenter.getCommonNavigation("2");
        if (lookFragment != null && uploadFragment != null) {
            lookFragment.setRefresh();
            uploadFragment.setRefresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            HashMap<String, String> map = messageEvent.getHashMap();
            if(map.containsKey("DocumentPreview_error")){
                for (int i = 0; i < dynamicEntities.size(); i++) {
                    if (1 == dynamicEntities.get(i).getItemType()) {
                        if (dynamicEntities.get(i).getDataBase().getDataCode().equals(map.get("DocumentPreview_error"))) {
                            dynamicEntities.get(i).getDataBase().setError(true);
                        }
                    }
                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("refreshAccount".equals(msg)) {
                //更新账户了
                if (homePagePresenter == null) {
                    return;
                }
                pageNum = 1;
                isEnd = false;
                FileUtilss.deleteWaterMarkBg(mContext, "watermark.jpg");
                FileUtilss.deleteWaterMarkBg(mContext, "watermarkBlack.jpg");
                homePagePresenter.checkLogin();
                homePagePresenter.getDynamicList(pageNum);
                homePagePresenter.getAllBanner();
                //水印只有启动和切换账号才获取
                homePagePresenter.getWatermarkList();
                //ossKey切换账号才获取
                homePagePresenter.getOSSkey();
                //获取导航切换账号才获取
                navigationEntityList.clear();
                //切换账号获取各公司的计费规则
                homePagePresenter.getCostConfig();
            } else if ("scrollToNews".equals(msg)) {
                consecutiveScrollerLayout.scrollToChild(llBanner);
            } else if ("RefreshGallery".equals(msg)||"RefreshVideo".equals(msg)) {
                if (uploadFragment != null) {
                    uploadFragment.setRefresh();
                }
            }else if ("LookFragment_No_Data".equals(msg)) {
                setLookUpload(0);
            } else if ("LookFragment_Have_Data".equals(msg)) {
                setLookUpload(1);
            } else if ("UploadFragment_No_Data".equals(msg)) {
                setLookUpload(2);
            } else if ("UploadFragment_Have_Data".equals(msg)) {
                setLookUpload(3);
            }
        }
    }

    private void setLookUpload(int type) {
        //0是 look无数据  1有数据    2upload无数据 3有数据
        if (type == 0) {
            if (titles.size() == 1) {
                if (titles.get(0).equals("最近浏览")) {
                    //清除自己
                    titles.remove(0);
                    fragments.remove(0);
                    commonNavigator.notifyDataSetChanged();
                    pagerAdapter.notifyDataSetChanged();
                    ll_look_upload.setVisibility(View.GONE);
                    ll_look_upload_space.setVisibility(View.GONE);
                }
            } else if (titles.size() == 2) {
                viewPager.setCurrentItem(1);
                titles.remove(0);
                fragments.remove(0);
                commonNavigator.notifyDataSetChanged();
                pagerAdapter.notifyDataSetChanged();
            }else{
                ll_look_upload.setVisibility(View.GONE);
                ll_look_upload_space.setVisibility(View.GONE);
            }
        } else if (type == 1) {
            if (titles.size() == 0) {
                titles.add("最近浏览");
                fragments.add(lookFragment);
                commonNavigator.notifyDataSetChanged();
                pagerAdapter.notifyDataSetChanged();
                ll_look_upload.setVisibility(View.VISIBLE);
                ll_look_upload_space.setVisibility(View.VISIBLE);
            } else if (titles.size() == 1) {
                if (titles.get(0).equals("最近上传")) {
                    titles.add(0, "最近浏览");
                    fragments.add(0, lookFragment);
                    commonNavigator.notifyDataSetChanged();
                    pagerAdapter.notifyDataSetChanged();
                    viewPager.setCurrentItem(0);
                    ll_look_upload.setVisibility(View.VISIBLE);
                    ll_look_upload_space.setVisibility(View.VISIBLE);
                }
            }else{
                ll_look_upload.setVisibility(View.VISIBLE);
                ll_look_upload_space.setVisibility(View.VISIBLE);
            }
        } else if (type == 2) {
            if (titles.size() == 1) {
                if (titles.get(0).equals("最近上传")) {
                    //清除自己
                    titles.remove(0);
                    fragments.remove(0);
                    commonNavigator.notifyDataSetChanged();
                    pagerAdapter.notifyDataSetChanged();
                    ll_look_upload.setVisibility(View.GONE);
                    ll_look_upload_space.setVisibility(View.GONE);
                }
            } else if (titles.size() == 2) {
                viewPager.setCurrentItem(0);
                titles.remove(1);
                fragments.remove(1);
                commonNavigator.notifyDataSetChanged();
                pagerAdapter.notifyDataSetChanged();

            }else{
                ll_look_upload.setVisibility(View.GONE);
                ll_look_upload_space.setVisibility(View.GONE);
            }
        } else if (type == 3) {
            if (titles.size() == 0) {
                titles.add("最近上传");
                fragments.add(uploadFragment);
                commonNavigator.notifyDataSetChanged();
                pagerAdapter.notifyDataSetChanged();
                ll_look_upload.setVisibility(View.VISIBLE);
                ll_look_upload_space.setVisibility(View.VISIBLE);
            } else if (titles.size() == 1) {
                if (titles.get(0).equals("最近浏览")) {
                    titles.add("最近上传");
                    fragments.add(uploadFragment);
                    commonNavigator.notifyDataSetChanged();
                    pagerAdapter.notifyDataSetChanged();
                    viewPager.setCurrentItem(1);
                    ll_look_upload.setVisibility(View.VISIBLE);
                    ll_look_upload_space.setVisibility(View.VISIBLE);
                }
            }else{
                ll_look_upload.setVisibility(View.VISIBLE);
                ll_look_upload_space.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    public void loadMineInfo(MineInfoEntity data) {
        if (data != null) {
            if (tvName == null) {
                return;
            }
            GlideUtils.loadAvatar(mContext, data.getHeadPhotoThumbUrl(), ivHead);
            tvName.setText(data.getNickName());
            if (mContext.getPackageName().equals("com.zhaofengnum")) {
                tvCompany.setText(mContext.getResources().getString(R.string.app_name));
                Glide.with(mContext).load(GlideUtils.loadLogoId(mContext)).into(ivCompany);
            }else{
                String companyLogo = new ShareUtils().getString(mContext, StaticClass.COMPANYLOGO, "");
                if (!Utils.isNull(companyLogo)) {
                    GlideUtils.load(mContext, companyLogo, ivCompany, R.drawable.default_news);
                } else {
                    Glide.with(mContext).load(GlideUtils.loadLogoId(mContext)).into(ivCompany);
                }
                tvCompany.setText(new ShareUtils().getString(mContext, StaticClass.COMPANYNAME, ""));
            }
            tvLevel.setText(data.getLvlName());
            if (!Utils.isNull(data.getLvlImage())) {
                String url = data.getLvlImage();
                GlideUtils.load(mContext, url, ivLevel, R.drawable.icon_wangzhe_23);
            }
            tvKnowledgeNum.setText(Utils.changeNumber(data.getScore()) + "");
            tvRanking.setText(Utils.changeNumber(data.getRankNum()) + "");
            int allScore = Utils.changeNumber(data.getTotalScore());
            int score = Utils.changeNumber(data.getScore());
            if (allScore > 0) {
                progressBar.setMax(allScore);
                progressBar.setProgress(score);
            }
            new ShareUtils().putString(mContext, StaticClass.APPACCOUNT, data.getAppAccount());
            new ShareUtils().putString(mContext, StaticClass.POST, data.getPost());
            new ShareUtils().putString(mContext, StaticClass.DEVICENAME, data.getBindingDeviceName());
            new ShareUtils().putString(mContext, StaticClass.ORIGINALURL, data.getHeadPhotoUrl());
            new ShareUtils().putString(mContext, StaticClass.USER_AVATAR_URL, data.getHeadPhotoThumbUrl());
            new ShareUtils().putString(mContext, StaticClass.USER_NICKNAME, data.getNickName());
            new ShareUtils().putString(mContext, StaticClass.BELG_ORG_CODE, data.getBelgOrgCode());
            new ShareUtils().putString(mContext, StaticClass.BELG_ORG_NAME, data.getBelgOrgName());
            new ShareUtils().putString(mContext, StaticClass.BELG_CATALOG_CODE, data.getBelgCatalogCode());
        }

    }

    @Override
    public void loadBanner(List<HomeBannerEntity> data) {
        if (llBanner == null) {
            return;
        }
        if (data != null) {
            if (data.size() > 0) {
                llBanner.setVisibility(View.VISIBLE);
                homeBanner.setAdapter(new BannerImageAdapter<HomeBannerEntity>(data) {
                    @Override
                    public void onBindView(BannerImageHolder holder, HomeBannerEntity data, int position, int size) {
                        //图片加载自己实现
                        GlideUtils.loadCustomRound(mContext, data.getBannerUrl(), (ImageView) holder.itemView, 4);
                        holder.imageView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(mContext, WebCommonActivity.class);
                                intent.putExtra("url", data.getJumpUrl());
                                mContext.startActivity(intent);
                            }
                        });
                    }
                }).addBannerLifecycleObserver(this)
                        .setBannerRound(Utils.dip2px(mContext, 6))
                        .setIndicator(new CircleIndicator(mContext));
            } else {
                llBanner.setVisibility(View.GONE);
            }
        } else {
            llBanner.setVisibility(View.GONE);
        }
    }


    @Override
    public void loadDynamicList(List<DynamicEntity> data) {
        loadEnd();
        if (pageNum == 1) {
            dynamicEntities.clear();
            dynamicAdapter.notifyDataSetChanged();
        }
        if (data != null) {
            if (data.size() == 0) {
                isEnd = true;
            }
            int old = dynamicEntities.size();
            List<DynamicEntity> newDynamicEntitys = new ArrayList<>();
            newDynamicEntitys.addAll(data);
            for (int i = 0; i < newDynamicEntitys.size(); i++) {
                int type = Utils.changeNumber(newDynamicEntitys.get(i).getResourceType());
                if (type > 5) {
                    //防止意外多余的类型出现，统一当做新闻处理
                    type = 4;
                }
                if(getActivity().getResources().getString(R.string.app_knowledge_name).equals(new ShareUtils().getString(mContext, StaticClass.COMPANYNAME,""))){
                    //应付华为市场所以不显示视频
                    if(type==3||type==2){
                        newDynamicEntitys.remove(i);
                        if (i < newDynamicEntitys.size()) {
                            i--;
                        }
                    }else{
                        newDynamicEntitys.get(i).setItemType(type);
                    }
                }else{
                    newDynamicEntitys.get(i).setItemType(type);
                }
            }
            dynamicEntities.addAll(newDynamicEntitys);
            dynamicAdapter.notifyItemRangeChanged(old, newDynamicEntitys.size());
        }
        if (dynamicEntities.size() == 0) {
            dynamicAdapter.setEmptyView(emptyView);
        } else {
            tvDynamic.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void loadNavigationsList(List<NavigationEntity> data) {
        if (rcvFunction == null) {
            return;
        }
        if (data != null) {
            navigationEntityList.clear();
            List<NavigationEntity> newData = NavigationTools.getNavigation(mContext,data, 1);
            navigationEntityList.addAll(newData);
            navigationAdapter.notifyDataSetChanged();
            rcvFunction.setVisibility(View.VISIBLE);
        }
        if (navigationEntityList.size() == 0) {
            rcvFunction.setVisibility(View.GONE);
        }
    }

    @Override
    public void loadNavigationsListNum(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            for (int i = 0; i < navigationEntityList.size(); i++) {
                if (jsonObject.has(navigationEntityList.get(i).getNavigationCode())) {
                    navigationEntityList.get(i).setNum(jsonObject.getString(navigationEntityList.get(i).getNavigationCode()));
                }
            }
            navigationAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void loadGalleryList(List<GalleryListEntity.ImagePathListBean> data) {
        //图片列表
        if (recyclerPicView == null) {
            return;
        }
        if (data != null) {
            ll_pic.setVisibility(View.VISIBLE);
            ll_pic_space.setVisibility(View.VISIBLE);
            galleryList.clear();
            galleryList.addAll(data);
            galleryHomeAdapter.notifyDataSetChanged();
        }else{
            ll_pic.setVisibility(View.GONE);
            ll_pic_space.setVisibility(View.GONE);
        }
        if (galleryList.size() == 0) {
            ll_pic.setVisibility(View.GONE);
            ll_pic_space.setVisibility(View.GONE);
        }
    }

    @Override
    public void loadCommonFunctionList(List<NavigationEntity> data) {
        if (rcvCommonFunction == null) {
            return;
        }
        if (data != null) {
            commonFunctionList.clear();
            commonFunctionList.addAll(data);
            commonFunctionAdapter.notifyDataSetChanged();
            rcvCommonFunction.setVisibility(View.VISIBLE);
        }
        if (commonFunctionList.size() == 0) {
            rcvCommonFunction.setVisibility(View.GONE);
            ivCommonFunctionNoData.setVisibility(View.VISIBLE);
        } else {
            ivCommonFunctionNoData.setVisibility(View.GONE);
            rcvCommonFunction.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void loadOfficeToolsList(List<NavigationEntity> data) {
        if (rcvOfficeTool == null) {
            return;
        }
        if (data != null) {
            officeToolList.clear();
            officeToolList.addAll(data);
            officeToolAdapter.notifyDataSetChanged();
            rcvOfficeTool.setVisibility(View.VISIBLE);
        }
        if (officeToolList.size() == 0) {
            rcvOfficeTool.setVisibility(View.GONE);
            ivOfficeToolNoData.setVisibility(View.VISIBLE);
        } else {
            rcvOfficeTool.setVisibility(View.VISIBLE);
            ivOfficeToolNoData.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.ivHead, R.id.llCompany, R.id.tvPicMore, R.id.llLevel, R.id.llRanking, R.id.llCommonFunction, R.id.llOfficeTool, R.id.llSearch, R.id.llQrCode, R.id.llMore})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.ivHead:
                intent = new Intent(mContext, UserInfosActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.llCompany:
                //切换所属组织
                if(mContext.getPackageName().equals("com.zhaofengnum")){
                  return;
                }
                intent = new Intent(mContext, AccountActivity.class);
                startActivity(intent);
                break;
            case R.id.llLevel:
                intent = new Intent(mContext, WebCommonActivity.class);
                intent.putExtra("url", NavigationTools.getAllUrl(mContext, Urls.getCapacityAnalysisGrowth) + "&employeeCode=" + new ShareUtils().getString(mContext, StaticClass.EMPLOYEECODE, ""));
                intent.putExtra("title", "段位");
                startActivity(intent);
                break;
            case R.id.llRanking:
                intent = new Intent(mContext, ScoreRankActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.llCommonFunction:
            case R.id.llOfficeTool:
            case R.id.llMore:
                intent = new Intent(mContext, KnowledgeMoreFunctionActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.llSearch:
                intent = new Intent(mContext, SearchRecordActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.tvPicMore:
                //更多图库
                String   navigationCode1 = new ShareUtils().getString(mContext, StaticClass.BOTTOM_1_CODE, "13");
                String   navigationCode3 = new ShareUtils().getString(mContext, StaticClass.BOTTOM_3_CODE, "14");
                if (navigationCode1.equals("26")) {
                    EventBus.getDefault().post(new MyEvent("HomeBottom1"));
                } else if (navigationCode3.equals("26")) {
                    EventBus.getDefault().post(new MyEvent("HomeBottom3"));
                } else {
                    intent = new Intent(mContext, NavigationBaseActivity.class);
                    intent.putExtra("type", 26);
                    mContext.startActivity(intent);
                }
                break;
            case R.id.llQrCode:
                new IntentIntegrator(getActivity())
                        .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选：一维码，二维码，一/二维码
                        .setPrompt("请对准二维码")// 设置提示语
                        .setCameraId(0)// 选择摄像头,可使用前置或者后置
                        .setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
                        .setBarcodeImageEnabled(false)// 扫完码之后生成二维码的图片
                        .setOrientationLocked(false)//扫描方向固定
                        .setCaptureActivity(ScanActivity.class) // 设置自定义的activity是CustomActivity
                        .initiateScan();// 初始化扫码
                break;
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    //获取通知权限
    private void getNOTIFICATION() {
        if (!NotificationManagerCompat.from(mContext)
                .areNotificationsEnabled()) {
            new NoticeDialog(mContext, new ShareDialogListener() {
                @Override
                public void onClick() {
                    XXPermissions.with(mContext)
                            .permission(Permission.NOTIFICATION_SERVICE)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                }
                            });
                }
            }).show();
        }
    }

    @Override
    public void initImmersionBar() {
        if (getActivity() == null) {
            return;
        }
        ImmersionBar.with(getActivity())
                .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.grey_3)  /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                String tag = intent.getAction();
                for (int i = 0; i < dynamicEntities.size(); i++) {
                    if (1 == dynamicEntities.get(i).getItemType()) {
                        if (dynamicEntities.get(i).getDataBase().getDataCode().equals(recevierDataCode)) {
                            if (!dynamicEntities.get(i).isOpen()) {
                                if (encryptStatus) {
                                    dynamicEntities.get(i).setOpen(true);
                                }
                                dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName, tag);
                            }

                        }

                    }

                }
            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName, String newTag) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                startActivity(newIntent);

            }
        } else {
            if (percent > 0 && percent < 100) {

                if (dynamicAdapter != null) {
                    if (1 == dynamicEntities.get(position).getItemType()) {
                        dynamicEntities.get(position).getDataBase().setProgress(percent);
                        dynamicAdapter.notifyItemChanged(position);
                    }
                }

            } else if (percent == 100) {

                if (dynamicAdapter != null) {
                    if (1 == dynamicEntities.get(position).getItemType()) {
                        dynamicEntities.get(position).getDataBase().setProgress(100);
                        dynamicAdapter.notifyItemChanged(position);
                        new Thread() {
                            @Override
                            public void run() {
                                AESEncrypt.encryptFile(mContext, fileUrl, fileName, recevierDataCode, newTag);
                            }
                        }.start();
                    }
                }

            } else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(DYNAMICTAG);// 获取数据
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (unbinder != null) {
            unbinder.unbind();
        }
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
        }

    }
}
